﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ObjectContextExtensions.cs" company="Collaboris Ltd.">
//   Copyright (c) Collaboris Ltd. All rights Reserved.
// </copyright>
// <summary>
//   The object context extensions.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Collaboris.DataAccess.Linq
{
    #region Imports

    using System;
    using System.Collections.Generic;
    using System.Data.Metadata.Edm;
    using System.Data.Objects;
    using System.Linq;

    #endregion

    /// <summary>
    /// The object context extensions.
    /// </summary>
    internal static class ObjectContextExtensions
    {
        /// <summary>
        /// The get ancestors.
        /// </summary>
        /// <typeparam name="T">
        /// </typeparam>
        /// <returns>
        /// </returns>
        private static IEnumerable<Type> GetAncestors<T>()
        {
            Type current = typeof(T);

            do
            {
                yield return current;

                current = current.BaseType;
            }
 while (current != typeof(object));
        }

        /// <summary>
        /// The get entity set name.
        /// </summary>
        /// <param name="dataContext">
        /// The data context.
        /// </param>
        /// <typeparam name="T">
        /// </typeparam>
        /// <returns>
        /// The get entity set name.
        /// </returns>
        public static string GetEntitySetName<T>(this ObjectContext dataContext)
        {
            /*
            EntityContainer container =

            dataContext.MetadataWorkspace.GetEntityContainer(dataContext.DefaultContainerName, DataSpace.CSpace);

            IEnumerable<Type> ancestors = GetAncestors<T>();

            EntitySet entitySet = container.BaseEntitySets.OfType<EntitySet>().Single

            (e => ancestors.Any(a => a.FullName == e.ElementType.FullName));

            return entitySet.Name;
*/
            EntityContainer container = dataContext.MetadataWorkspace.GetEntityContainer(dataContext.DefaultContainerName, DataSpace.CSpace);

            EntitySet entitySet = container.BaseEntitySets.OfType<EntitySet>().Where(e => e.ElementType.Name == typeof(T).Name).Single();

            return entitySet.Name;
        }
    }
}